<?php
/**
 * Created by PhpStorm.
 * User: qiaoli
 * Date: 15/11/2
 * Time: 下午5:01
 */
defined('BASEPATH') OR exit('No direct script access allowed');
class Messagem extends CI_Model
{
    const MSG_APP_TYPE_SYSTEM = 1;
    const MSG_APP_TYPE_PERSONAL = 2;
    const MSG_APP_TYPE_ATTENTION = 3;
    const MSG_APP_TYPE_INVITATION = 4;
    const MSG_APP_TYPE_CHAT = 5;
    const MSG_APP_TYPE_HELLO = 6;

    const MSG_MSG_TYPE_DONGTAI = 2;

    const CHAT_NOTICE_GROUP = 1;
    const CHAT_NOTICE_AUDIT = 2;


    function __construct()
    {
        parent::__construct();
    }
    
    function send_message($post_id,$receive_uid,$content, $from_uid=0, $apptype=self::MSG_APP_TYPE_PERSONAL)
    {
        if (! isset($this->userm)) {
            $this->load->model('userm');
        }
        $send_message_array = array();

        // post_type_extend, 帖子类型(1:病例分享，2：疑难求助，3：快速求助，4：文字提问，5：投票，100：品牌)
        $info = $this->db->select('post_type_extend')->where('id', $post_id)->from('ml_post')->get()->row_array();
        $post_type_extend = isset($info["post_type_extend"]) ? $info["post_type_extend"] : 0;

        if ($post_type_extend) {
            $tmp_arr = array();
            if (is_array($receive_uid)) {
                $receive_users = $this->userm->getUserInfoByIds($receive_uid);

                foreach ($receive_users as $receive_user) {
                    if (version_compare($receive_user["softversion"], '2.2.0') < 0 && ($post_type_extend == 5 || $post_type_extend == 6)) {
                        continue;
                    }
                    $tmp_arr[] = $receive_user["id"];
                }
            }
            else {
                $receive_user = $this->userm->getUserInfoById($receive_uid);
                if (version_compare($receive_user["softversion"], '2.2.0') < 0 && ($post_type_extend == 5 || $post_type_extend == 6)) {
                    // pass
                }
                else {
                    $tmp_arr = $receive_user["id"];
                }
            }

            if (empty($tmp_arr)) {
                return array("code"=>-100, 'tips'=>"接收用户版本过低");
            }

            $receive_uid = $tmp_arr;
            $send_message_array['post_type_extend'] = $post_type_extend;
        }

        if (!isset($this->postm)) {
            $this->load->model('postm');
        }

        $post_first_img = "";
        if ($post_type_extend != 4 && $post_type_extend != 5) {
            //问答和投票么有图
            $post_first_img = $this->postm->get_post_first_img($post_id);
            $post_first_img = ret_fullpath_url($post_first_img);
        }
        elseif ($send_message_array['post_type_extend'] == 4) {
            $post_first_img = Postm::POST_IMG_ANSWER;
        }
        elseif ($send_message_array['post_type_extend'] == 5) {
            $post_first_img = Postm::POST_IMG_VOTE;
        }

        $send_message_array['post_first_img'] = $post_first_img;
        $send_message_array['post_id'] = (string)$post_id;
        $send_message_array['content'] = $content;

        $send_message_string = json_encode($send_message_array);

        $from_uid = $from_uid ? $from_uid : $this->uid;     // 如果此时 from_uid 仍为空, 消息将发送失败

        $ret = $this->send_msg_basic($from_uid, $receive_uid, $send_message_string, $apptype);

        return $ret;
    }

    public function update_msg_content($msg_id, $message_array)
    {
        $this->load->library('curl');

        $message_url = MESSAGE_URL.'v1/editmsg.json';

        $message_data = array("msg_id"=> $msg_id);
        $message_data["message"] = json_encode($message_array);

        $ret = $this->curl->simple_post($message_url,$message_data);

        return $ret;
    }


    public function build_group_chat_msg($icon, $title, $body, $gid, $from, $apply_status) {
        return array(
            "icon"=> $icon,                        // 左侧 icon
            "title"=> $title,                      // 上方标题
            "body"=> $body,                        // 中部消息
            "gid"=> $gid,                          // 群 id
            "from"=> $from,                        // 来自
            "apply_status"=> $apply_status,        // 1申请中2拒绝3通过
        );
    }

    public function send_chat_msg($from, $to, $send_message_array, $msgtype)
    {
        // 发入群相关通知
        $send_message_string = json_encode($send_message_array);

        // $msgtype: 默认为1别人申请我的群, 2我发出的申请
        $ret = $this->send_msg_basic($from, $to, $send_message_string, self::MSG_APP_TYPE_CHAT, $msgtype);

        return $ret;
    }


    /**
     * @param $from
     * @param $to array|int: 发给
     * @param $message  string
     * @param int $apptype
     * @param int $msgtype: 消息类型,默认1, 1传统消息, apptype=2&&msgtype=2 动态相关提醒 新类型3  作为纯文字信息 不跳转
     * @param string $subject
     * @return mixed
     */
    public function send_msg_basic($from, $to, $message, $apptype=self::MSG_APP_TYPE_PERSONAL, $msgtype=1, $subject='无题')
    {
        if(!is_string($message)) return false;  //这里的message 必须得是json格式字符串
        $this->load->model('clear_cachem');
        $this->clear_cachem->clear_msg_count($to, $apptype);

        $message_url = MESSAGE_URL.'v1/sendmsg.json';

        $post_message_data = array();
        $post_message_data['fromuid'] = $from; //发送人UID
        $post_message_data['touids'] = $to; //接受人UID
        $post_message_data['message'] = $message;   //消息体

        $post_message_data['type'] = 0;             //（0系统消息, 1二人对话）
        $post_message_data['apptype'] = $apptype;   //分配的apptype
        $post_message_data['msgtype'] = $msgtype;   //消息类型
        $post_message_data['subject'] = $subject;   //消息主题（可为空）
        $post_message_data['fromusername'] = "";    //发送者名称（可为空）
        $post_message_data['op'] = 'sendpm';        //发送类型（必须为sendpm）
        //w_log("发送的数据为  ".json_encode($post_message_data));
        //开始发送消息
        $this->load->library('curl');
        $ret = $this->curl->simple_post($message_url,$post_message_data);

        if ($ret) {
            $message = json_decode($ret, 1);
            return $message;
        }
        return array();
    }


    /**
     * 动态发消息
     * @param $fromuid
     * @param array|int $touids
     * @param string $title
     * @param $cont
     * @return mixed
     */
    public function snd_dongtai($fromuid, $touids, $event_id, $title = "", $cont) {

        $comment_send_message_array = array('content'=>$cont, "event_id"=>$event_id);
        if ($title) {
            $comment_send_message_array["title"] = $title;
        }

        $comment_send_message_string = json_encode($comment_send_message_array);

        return $this->send_msg_basic($fromuid, $touids, $comment_send_message_string, self::MSG_APP_TYPE_PERSONAL, self::MSG_MSG_TYPE_DONGTAI);
    }

    /**
     * @param $user_id
     * @param array $typ_arr
     * @return array 返回以请求中的apptype为key的数组
     */
    public function msg_count($user_id, $typ_arr)
    {
        if (empty($typ_arr)) {
            return array();
        }

        $cache_non_arr = array();
        $cache_ok_arr = array();
        foreach ($typ_arr as $apptype) {
            $key = 'message_count_' . $user_id . "_" . $apptype;

            $cache = $this->mc->get($key);
            if (is_bool($cache) && $cache == false) {
                $cache_non_arr[] = $apptype;
            }
            else {
                $cache_ok_arr[$apptype] = $cache;
            }
        }
        if (empty($cache_non_arr)) {
            return $cache_ok_arr;
        }

        $param = implode(",", $cache_non_arr);
        $this->load->library('curl');

        $requrl = MESSAGE_URL . "v1/publicstatus.json?uid={$user_id}&apptype={$param}";
        $ret = $this->curl->simple_get($requrl);
        if (!$ret || $ret == '""') {
            foreach ($cache_non_arr as $apptype) {
                $cache_ok_arr[$apptype] = 0;
            }
        }
        else {
            $data = json_decode($ret, 1);
            foreach ($data as $apptype => $n) {
                $cache_ok_arr[$apptype] = $n;

                $key = 'message_count_' . $user_id . "_" . $apptype;
                $this->mc->save($key, $n, 3 * 60);
            }
        }
        
        return $cache_ok_arr;
    }

    
    public function get_msg_list($user_id, $apptype, $page, $page_size=20)
    {
        $this->load->library('curl');

        $requrl = MESSAGE_URL . "v1/publiclist.json?uid={$user_id}&apptype={$apptype}&page={$page}&sort=desc&page_size={$page_size}";

        $ret = $this->curl->simple_get($requrl);
        $message = array();
        if($ret)
        {
            $message = json_decode($ret,1);
        }

        if(version_compare($this->softversion, '2.2.0') < 0) {


            // flag_dongtai 为真, 需删除动态消息
            $flag_dongtai = false;
            if (version_compare($this->softversion, '2.0.0') < 0) {
                $flag_dongtai = true;
            }
            
            foreach($message as $k =>$itm) {
                if ($flag_dongtai) {
                    if (isset($itm["apptype"]) && $itm["apptype"] == self::MSG_APP_TYPE_PERSONAL && $itm["msgtype"] == self::MSG_MSG_TYPE_DONGTAI) {

                        // 去掉低于 2.0.0 以下与动态有关的消息
                        unset($message[$k]);
                    }
                }
                try {
                    // 
                    $msg = json_decode($itm["message"], true);
                    if (isset($msg["post_type_extend"]) && ($msg["post_type_extend"]==5 || $msg["post_type_extend"]==4)) {
                        unset($message[$k]);
                    }
                }
                catch (Exception $e) {
                    //
                }

                //2.2.0以下版本去掉个人消息里面的 图谱分享 msgtype=3
                if($itm["msgtype"] == 3)
                {
                    unset($message[$k]);
                }

            }
            $message = array_values($message);
        }
        //2.2.0 以后并且是系统消息 增加一个H5分享功能
        if(version_compare($this->softversion,'2.2.0') >= 0 && $apptype == self::MSG_APP_TYPE_SYSTEM)
        {
            $return = [];
                foreach($message as $k =>$itm) {
                    $itm['describe'] = $itm['subject'];
                    $itm['share_desc'] = $itm['subject'];
                    $item = $itm;
                    $return[] = $item;
                }

            
            $message = $return;
        }

        //邀请列表需要增加一个 帖子类别
        if($apptype == self::MSG_APP_TYPE_INVITATION)
        {
            $return = [];
            $this->load->model('postm');
            foreach($message as $k =>$itm) {
                $itm['share_desc'] = $itm['subject'];
                $msg = json_decode($itm["message"], true);
                if(empty($msg["post_type_extend"]))
                {
                    $post_info = $this->postm->get_one_post_4_search($msg['post_id'],$user_id);
                    $msg["post_type_extend"] = $post_info['post_type_extend'];
                    $itm['message'] = json_encode($msg);
                }
                $item = $itm;
                $return[] = $item;
            }
            $message = $return;
        }

        //2.4.0 聊天 判断 是否已经处理过
        if(version_compare($this->softversion,'2.4.0') >= 0 && $apptype == self::MSG_APP_TYPE_CHAT)
        {
            ci_load_once('imapim');
            foreach($message as $k =>$itm) {
                $msg = json_decode($itm['message'],1);
                $msg['apply_status'] =  $msg['apply_status']==3 ? 3:$this->imapim->get_apply_status($msg['gid'],$msg['from']);
                $message[$k]['message'] = json_encode($msg);

            }
        }

        $this->load->model('clear_cachem');
        $this->clear_cachem->clear_msg_count($user_id, $apptype);
        return $message;
    }
}